package xyz.lwm.lazycat.utility.convert;

/**
 * convert util
 *
 * @author lwm
 */
public abstract class Convert {

    /**
     * convert value to string
     *
     * @param value original value
     * @param <T> generic type
     * @return string value
     */
    @SuppressWarnings("unchecked")
    public static <T> String toString(T value) {
        return value == null ? null : ((Converter<T>) Converters.getConverter(value.getClass())).toString(value);
    }

    /**
     * convert string value to new type
     *
     * @param value original value
     * @param type new type
     * @param <T> generic type
     * @return string value
     */
    public static <T> T fromString(String value, Class<T> type) {
        return Converters.getConverter(type).fromString(value);
    }

    /**
     * convert value to new type
     *
     * @param value original value
     * @param type new type
     * @return new value
     * @param <T> new type
     */
    @SuppressWarnings("unchecked")
    public static <T> T to(Object value, Class<T> type) {
        if (value == null) {
            return null;
        } else if (type.isAssignableFrom(value.getClass())) {
            return (T) value;
        } else {
            return fromString(toString(value), type);
        }
    }

}
